package com.hr.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hr.entity.User;
import com.hr.service.UserService;
import com.hr.utils.ConstantUtil;
import com.hr.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author hr
 * @since 2021-10-15
 */
@CrossOrigin
@RestController
@RequestMapping("/hr/service/user")
public class UserController {

    @Autowired
    UserService userService;

    @PostMapping("login")
    public R login(@RequestBody User user, String type) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", user.getUsername());
        wrapper.eq("password", user.getPassword());
        User one = userService.getOne(wrapper);
        if(one == null) {
            return R.error().message("用户名或密码错误");
        }
        if(type != null && type.equals("admin") && one.getRole() == 1) {
            return R.error().message("用户没有该权限");
        } else if(type != null && type.equals("user")) {
            ConstantUtil.CURRENT_USER = one.getId();
        }
        return R.ok().data("token", one.getId());
    }

    @PostMapping("logout")
    public R logout() {
        return R.ok().message("登出成功");
    }

    @GetMapping("info")
    public R info(String token, String type) {
        System.out.println(token);
        User user = userService.getById(token);
        if(type != null && type.equals("user")) {
            ConstantUtil.CURRENT_USER = user.getId();
        }
        return R.ok().data("roles", user.getRole() == 1 ? "[admin]" : "[user]")
                .data("name", user.getUsername())
                .data("avatar", "https://guli-aaa.oss-cn-hangzhou.aliyuncs.com/cat.jpeg");
    }

    @GetMapping("/users/{cur}/{limit}")
    public R getUsers(@PathVariable("cur") long cur,
                      @PathVariable("limit") long limit,
                      String userName){
        Page<User> page = new Page<>(cur, limit);
        QueryWrapper<User> wrapper = new QueryWrapper<>();

        if(!StringUtils.isEmpty(userName)) {
            wrapper.like("username", userName);
        }

        userService.page(page, wrapper);

        long total = page.getTotal();
        List<User> records = page.getRecords();
        return R.ok().data("total", total).data("rows", records);
    }

    @GetMapping("/user")
    public R getUserById(Integer id){
        User user = userService.getById(id);
        user.setPassword(null);
        return R.ok().data("user", user);
    }

    @PutMapping("/user")
    public R updateUserById(@RequestBody User user) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", user.getUsername());
        User one = userService.getOne(wrapper);
        if(one != null && !one.getId().equals(user.getId())) {
            return R.error().message("用户名重复");
        }
        boolean update = userService.updateById(user);
        return update ? R.ok() : R.error();
    }

    @PostMapping("/user")
    public R saveUser(@RequestBody User user) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", user.getUsername());
        if(userService.getOne(wrapper) != null) {
            return R.error().message("用户名重复");
        }
        boolean save = userService.save(user);
        return save ? R.ok() : R.error().message("添加失败");
    }

    @DeleteMapping("/user/{id}")
    public R deleteUserById(@PathVariable("id") Integer id){
        boolean delete = userService.removeById(id);
        return delete ? R.ok() : R.error();
    }

    @PostMapping("/password/{oldPassword}/{newPassword}")
    public R updatePassword(@PathVariable("oldPassword") String oldPassword, @PathVariable("newPassword") String newPassword) {
        User user = userService.getById(ConstantUtil.CURRENT_USER);
        if(!user.getPassword().equals(oldPassword)) {
            return R.error().message("原密码错误");
        }
        else {
            user.setPassword(newPassword);
            boolean update = userService.updateById(user);
            return update ? R.ok() : R.error();
        }
    }

    @GetMapping("one")
    public R getOne(){
        System.out.println(ConstantUtil.CURRENT_USER);
        User user = userService.getById(ConstantUtil.CURRENT_USER);
        System.out.println(user);
        return R.ok().data("user", user);
    }

}

